package com.smart.support.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.smart.common.cache.CacheService;
import com.smart.common.entities.ajax.AjaxResult;
import com.smart.common.entities.constant.SmartConstant;
import com.smart.common.entities.file.UploadBody;
import com.smart.common.entities.file.UploadResult;
import com.smart.common.entities.option.SelectOption;
import com.smart.manager.product.repository.*;
import com.smart.manager.system.repository.ConfigRepository;
import com.smart.manager.work.entities.models.PigOrder;
import com.smart.manager.work.entities.models.PigOrderFoods;
import com.smart.manager.work.entities.models.query.QPigOrder;
import com.smart.manager.work.entities.models.query.QPigOrderFoods;
import com.smart.service.oss.AliYunFileHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author leo
 * @date 2023/09/06
 */
@Api(tags = "游戏管理公共资源")
@RestController
@RequestMapping(SmartConstant.MANAGER_API_PREFIX + "product/support")
@RequiredArgsConstructor
@Slf4j
public class Product {

    private final BasicPlaceRepository basicPlaceRepository;
    private final PigBreedRepository pigBreedRepository;
    private final PigLevelRepository pigLevelRepository;
    private final PropsProfileRepository propsProfileRepository;
    private final PropsComboRepository propsComboRepository;
    private final BasicRfidRepository basicRfidRepository;
    private final BasicCameraRepository basicCameraRepository;
    private final PropsServeRepository propsServeRepository;
    private final BasicCameraDetailRepository basicCameraDetailRepository;
    private final CacheService cacheService;
    private final AliYunFileHandler aliYunFileHandler;
    private final PigGoodsRepository pigGoodsRepository;
    private final PropsSnacksRepository propsSnacksRepository;
    private final ConfigRepository configRepository;

    @ApiOperation(value = "场地字典")
    @GetMapping("basicPlaceOptions")
    public AjaxResult<List<SelectOption>> basicPlaceOptions() {
        List<SelectOption> result = basicPlaceRepository.getOptions();
        return AjaxResult.data(result);
    }

    @ApiOperation(value = "品种字典")
    @GetMapping("pigBreedOptions")
    public AjaxResult<List<SelectOption>> pigBreedOptions() {
        List<SelectOption> result = pigBreedRepository.getOptions();
        return AjaxResult.data(result);
    }

    @ApiOperation(value = "日龄字典")
    @GetMapping("pigLevelOptions")
    public AjaxResult<List<SelectOption>> pigLevelOptions() {
        List<SelectOption> result = pigLevelRepository.getOptions();
        return AjaxResult.data(result);
    }

    @ApiOperation(value = "食物字典")
    @GetMapping("propsProfileOptions")
    public AjaxResult<List<SelectOption>> propsProfileOptions() {
        List<SelectOption> result = propsProfileRepository.getOptions();
        return AjaxResult.data(result);
    }

    @ApiOperation(value = "零食字典")
    @GetMapping("propsSnacksOptions")
    public AjaxResult<List<SelectOption>> propsSnacksOptions() {
        List<SelectOption> result = propsSnacksRepository.getOptions();
        return AjaxResult.data(result);
    }

    @ApiOperation(value = "套餐字典")
    @GetMapping("propsComboOptions")
    public AjaxResult<List<SelectOption>> propsComboOptions() {
        List<SelectOption> result = propsComboRepository.getOptions();
        return AjaxResult.data(result);
    }

    @ApiOperation(value = "服务字典")
    @GetMapping("propsServeOptions")
    public AjaxResult<List<SelectOption>> propsServeOptions() {
        List<SelectOption> result = propsServeRepository.getOptions();
        return AjaxResult.data(result);
    }

    @ApiOperation(value = "耳标字典")
    @GetMapping("basicRfidOptions")
    public AjaxResult<List<SelectOption>> basicRfidOptions() {
        List<SelectOption> result = basicRfidRepository.getOptions();
        return AjaxResult.data(result);
    }

    @ApiOperation(value = "商品字典")
    @GetMapping("pigGoodsOptions")
    public AjaxResult<List<SelectOption>> pigGoodsOptions() {
        List<SelectOption> result = pigGoodsRepository.getOptions();
        return AjaxResult.data(result);
    }

    @ApiOperation(value = "蓝牙耳标MAC字典")
    @GetMapping("beaconMacOptions")
    public AjaxResult<List<SelectOption>> beaconMacOptions() {
        List<SelectOption> result = basicRfidRepository.getRfidOptions();
        return AjaxResult.data(result);
    }

    @ApiOperation(value = "未绑定的摄像头")
    @GetMapping("basicCameraOptions")
    public AjaxResult<List<SelectOption>> basicCameraOptions() {
        List<SelectOption> result = basicCameraRepository.getOptions();
        return AjaxResult.data(result);
    }

    @ApiOperation(value = "未绑定的摄像头(通道)")
    @GetMapping("basicCameraDetailOptions")
    public AjaxResult<List<SelectOption>> basicCameraDetailOptions() {
        List<SelectOption> result = basicCameraDetailRepository.getOptions();
        return AjaxResult.data(result);
    }

    @ApiOperation("录制回调")
    @PostMapping("getRecord")
    public ResponseEntity<String> getRecord(@RequestBody String body) {
        JSON parse = JSONUtil.parse(body);
        Object messageId = parse.getByPath("header.messageId");
        Object type = parse.getByPath("header.type");
        if (type.equals("ys.open.cloud")) {
            //录制回放类型
            Object projectId = parse.getByPath("body.projectId");
            log.warn("projectId = {}", projectId);
            //录制完成回调
            if (parse.getByPath("body.messageType").equals("record_fragment_upload_file")) {
                log.warn("录制回调  {}", body);
                String string = cacheService.getDumpCache().get((String) parse.getByPath("body.taskId"));
                if (StrUtil.isNotBlank(string)) {
                    //转存
                    String accessToken = cacheService.getCameraTokenCache().get("accessToken");
                    Object fileId = parse.getByPath("body.fileId");
                    String url = "https://open.ys7.com/api/service/cloudrecord/file/official/download";
                    HttpResponse execute = HttpRequest.get(url).header("accessToken", accessToken).form(Map.of(
                            "fileId", fileId,
                            "projectId", projectId
                    )).execute();
                    String bodied = execute.body();
                    JSON json = JSONUtil.parse(bodied);
                    Object byPath = json.getByPath("data.urls");
                    String object = (String) JSONUtil.parseArray(byPath).get(0);
                    getFile(object,string);
//                    setFileLocal(object, string);
                }
            }
        }
        final ResponseEntity<String> resp = ResponseEntity.ok(JSONUtil.toJsonStr(Map.of("messageId", messageId)));
        log.info("返回的信息:{}", resp);
        return resp;
    }

    /**
     * @param url  转存地址
     * @param code 工单code
     */
    @Async
    public void getFile(String url, String code) {
        try {
            URLConnection conn = new URL(url).openConnection();
            InputStream inputStream = conn.getInputStream();
            UploadBody.ByteFile byteFile = new UploadBody.ByteFile().setData(inputStream.readAllBytes());
            UploadResult result = aliYunFileHandler.uploadMp4File(byteFile, "", "");

            PigOrderFoods one = new QPigOrderFoods().code.eq(code).setMaxRows(1).findOne();
            if (ObjUtil.isNotNull(one)){
                one.setVideo(result.getUrl()).update();
            }else {
                PigOrder one1 = new QPigOrder().code.eq(code).setMaxRows(1).findOne();
                if (ObjUtil.isNotNull(one1)){
                    one1.setVideo(result.getUrl()).update();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 转存本地
     *
     * @param url
     * @param code
     */
    @Async
    public void setFileLocal(String url, String code) {
        Optional<PigOrder> order = new QPigOrder().code.eq(code).setMaxRows(1).findOneOrEmpty();
        if (order.isPresent()) {
            String serverUrl = (String) configRepository.readCache("ServerConfig").get("url");
            String stockpile = (String) configRepository.readCache("ServerConfig").get("stockpile");
            String fastUUID = IdUtil.fastUUID();
            String getUrl = "oss/" + fastUUID + ".mp4";
            log.warn("stockpile+getUrl = {}",stockpile+getUrl);
            String complete = serverUrl + getUrl;
            try {
                // 创建 URL 对象并打开连接
                URL fileUrl = new URL(url);
                HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection();
                // 获取输入流
                InputStream inputStream = connection.getInputStream();
                // 将 InputStream 写入文件
                Path path = Path.of(stockpile+getUrl);
                Files.copy(inputStream, path, StandardCopyOption.REPLACE_EXISTING);
                // 关闭连接和输入流
                inputStream.close();
                connection.disconnect();
                order.get().setVideo(complete).update();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
